import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:ycbl/config/bl_color.dart';
import 'package:ycbl/config/bl_style.dart';

/// 日历显示的类型
enum BLCalenderType { week, month }

/// 学习中心日历
class BLLearnCalender extends StatefulWidget {

  /// 日历控制器
  final CalendarController calendarController;
  /// 事件
  final Map<DateTime, List> events;
  /// 选中某天的回调
  final OnDaySelected onDaySelected;
  /// 日历翻页回调
  final OnVisibleDaysChanged onVisibleDaysChanged;
  /// 日历初始化完成回调
  final OnVisibleDaysChanged onCalendarCreated;
  /// 日历显示的类型：周日历 or 月日历
  final BLCalenderType calendarType;
  /// 初始化显示的日期
  final DateTime initialSelectedDay;

  /// 构建学习中心日历
  const BLLearnCalender({
    Key key,
    @required this.calendarController,
    this.events,
    this.onDaySelected,
    this.onVisibleDaysChanged,
    this.onCalendarCreated,
    this.calendarType,
    this.initialSelectedDay,
  }) : super(key: key);


  @override
  _BLLearnCalenderState createState() => _BLLearnCalenderState();
}

class _BLLearnCalenderState extends State<BLLearnCalender> {

  /// 日历文字的样式
  final TextStyle _calendarTextStyle = BLStyle.commonBlackTextStyle;
  /// 屏幕宽度，用来粗略估算左右翻页按钮的 margin，默认情况下左右按钮在日期的最两侧
  double _screenWidth;
  /// 标题日期和按钮的颜色
  final Color _headerIconColor = Color(0xFFF03F00);
  /// 日历周几对应的中文标题
  final _weeks = {
    1 : '一',
    2 : '二',
    3 : '三',
    4 : '四',
    5 : '五',
    6 : '六',
    7 : '日',
  };
  

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return buildCalendar();
  }
  
  bool _isWeekType() {
    return widget.calendarType == BLCalenderType.week;
  }

  /// 日历
  Widget buildCalendar() {

    return TableCalendar(
      calendarController: widget.calendarController,
      //locale: 'zh_CN', // 需要在 main 中调用 initializeDateFormatting
      initialSelectedDay: widget.initialSelectedDay,
      events: widget.events ?? [],
      //下面两句搭配用来固定日历的样式：显示 周日历 or 月日历
      initialCalendarFormat: _isWeekType() ? CalendarFormat.week : CalendarFormat.month,
      availableCalendarFormats: _isWeekType() ? const { //只显示周日历
        CalendarFormat.week:'' 
      } : const { //只显示月日历
        CalendarFormat.month:''  
      } ,
      //设置每周的开始为周日还是周一
      startingDayOfWeek: StartingDayOfWeek.monday,
      // headerVisible: false, // header（日期导航） 是否可见
      // 这里使用自带的 header （日期导航），如果你希望自定义，
      // 那么就设置 headerVisible: false 来隐藏自带的 header，
      // 并自定义实现你期望的 header
      headerStyle: HeaderStyle(
        //日期标题居中
        centerHeaderTitle: true,
        formatButtonVisible: false,
        //左、右侧翻页按钮
        leftChevronIcon: Icon(
          Icons.arrow_left,
          color: _headerIconColor,
        ),
        rightChevronIcon: Icon(
          Icons.arrow_right,
          color: _headerIconColor,
        ),
        //左右按钮内边距
        leftChevronPadding: EdgeInsets.all(0),
        rightChevronPadding: EdgeInsets.all(0),
        // 设置外边距 让按钮尽量都靠近标题
        leftChevronMargin: EdgeInsets.only(left: _screenWidth / 5),
        rightChevronMargin:EdgeInsets.only(right: _screenWidth / 5) ,
        //格式化日期标题
        titleTextBuilder: (DateTime date, dynamic locale) {
          return formatDate(date, ['yyyy', '年', 'mm', '月']);
        },
        //标题样式
        titleTextStyle: TextStyle(
          color: _headerIconColor,
          fontSize: 16,
        ),
        //设置 header 背景色
        decoration: BoxDecoration(
          color: Color(0xFFFEEDE4),
        ),
      ),

      calendarStyle: CalendarStyle(
        //日历内容（header 以下位置）边距
        contentPadding: EdgeInsets.fromLTRB(10, 16, 10, 10),
        //日历中各文字的样式
        weekdayStyle: _calendarTextStyle,
        weekendStyle: _calendarTextStyle,
        outsideStyle: _calendarTextStyle,
        outsideWeekendStyle: _calendarTextStyle,
        outsideDaysVisible: false, //本月以外的日期不可见
      ),
      daysOfWeekStyle: DaysOfWeekStyle(
        // ‘周几’文字样式
        weekdayStyle: _calendarTextStyle,
        weekendStyle: _calendarTextStyle,
        dowTextBuilder: (DateTime date, dynamic locale) {
          return _weeks[date.weekday] ?? '';
        }
      ),

      // 自定义日期显示
      builders: CalendarBuilders(
        // 绘制选中日期
        selectedDayBuilder: (context, date, _) {
          return Container(
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                    colors: [Color(0xFFFF7500), Color(0xFFFF9100),],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter
                )
            ),
            margin: EdgeInsets.all(8),
            child: Center(
              child: Text(
                widget.calendarController.isToday(date) ? '今' : '${date.day}',
                style: _calendarTextStyle.copyWith(color: BLColor.whiteColor),
              ),
            ),
          );
        },
        //绘制今天
        todayDayBuilder: (context, date, _) {
          return Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Color(0xFFFF9100),),
            ),
            margin: EdgeInsets.all(8),
            child: Center(
              child: Text(
                '今',
                style: _calendarTextStyle.copyWith(color: Color(0xFFFF9100)),
              ),
            ),
          );
        },
        //绘制 marker（event、 holidays）
        markersBuilder: (context, date, events, holidays) {
          final children = <Widget>[];
          if (events.isNotEmpty) {
            children.add(
              Positioned(
                right: 4,
                top: 2,
                child: Container(
                  decoration: BoxDecoration(
                    color: Color(0xFFF7D9C9),
                    shape: BoxShape.circle,
                  ),
                  padding: EdgeInsets.all(4),
                  child: Text(
                    '${events.length}',
                    style: TextStyle(
                      color: Color(0xFFE95F12),
                      fontSize: 10,
                    ),
                  ),
                ),
              ),
            );
          }

          return children;
        },
      ),
      //日期选中回调
      onDaySelected: widget.onDaySelected,
      //日历翻页回调
      onVisibleDaysChanged: widget.onVisibleDaysChanged,
      //日历创建回调
      onCalendarCreated: widget.onCalendarCreated,
    );
  }
}
